package main
 
import (
	"log"
 
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
)
 
type family struct {
	Id   int    `gorm:"primary_key"`
	Name string `gorm:"type:varchar(100);not null;index:ip_idx"`
	Sex  string    `gorm:"type:varchar(50);"not null"`
	Dep string `gorm:"type:varchar(100);not null;"`
}
 
func main() {
	//连接数据库
	db, err := gorm.Open("postgres", "host=127.0.0.1 port=5432 user=postgres dbname=people password=lixiuyu sslmode=disable")
	if err != nil {
		log.Println(err)
	} else {
		log.Println("连接成功！")
	}
	defer db.Close()
 
	//创建表family
	if !db.HasTable(&family{}) {
		if err := db.CreateTable(&family{}).Error; err != nil {
			panic(err)
		} else {
			log.Println("创建成功！")
		}
	}
 
	//插入数据
	user := &family{
		Id:   2,
		Name: "宋美龄",
		Sex:  "女",
		Dep: "蒋介石妻子",
	}
	if err := db.Create(user).Error; err != nil {
		log.Println("插入失败！", err)
		return
	} else {
		log.Println("插入成功！")
	}
 
 
}

